/*
 * Copyright 2002-2015 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.dao.annotation;

import java.lang.annotation.Annotation;

import org.springframework.aop.framework.autoproxy.AbstractBeanFactoryAwareAdvisingPostProcessor;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;

/**
 * Bean post-processor that automatically applies persistence exception translation to any
 * bean marked with Spring's @{@link org.springframework.stereotype.Repository Repository}
 * annotation, adding a corresponding {@link PersistenceExceptionTranslationAdvisor} to
 * the exposed proxy (either an existing AOP proxy or a newly generated proxy that
 * implements all of the target's interfaces).
 *
 * <p>Translates native resource exceptions to Spring's
 * {@link org.springframework.dao.DataAccessException DataAccessException} hierarchy.
 * Autodetects beans that implement the
 * {@link org.springframework.dao.support.PersistenceExceptionTranslator
 * PersistenceExceptionTranslator} interface, which are subsequently asked to translate
 * candidate exceptions.
 *

 * <p>All of Spring's applicable resource factories (e.g.
 * {@link org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean})
 * implement the {@code PersistenceExceptionTranslator} interface out of the box.
 * As a consequence, all that is usually needed to enable automatic exception
 * translation is marking all affected beans (such as Repositories or DAOs)
 * with the {@code @Repository} annotation, along with defining this post-processor
 * as a bean in the application context.
 *
 * @author Rod Johnson
 * @author Juergen Hoeller
 * @since 2.0
 * @see PersistenceExceptionTranslationAdvisor
 * @see org.springframework.stereotype.Repository
 * @see org.springframework.dao.DataAccessException
 * @see org.springframework.dao.support.PersistenceExceptionTranslator
 */
/*
1. PersistenceExceptionTranslationPostProcessor 总结
	持久化异常转换处理器 - 自动为带有@Repository注解的Bean应用持久化异常转换的Bean后置处理器
	自动异常翻译 - 将原生资源异常转换为Spring的DataAccessException层次结构
	零配置集成 - 与Spring的持久化基础设施无缝集成，只需添加@Repository注解


	| 原生异常 | 转换后的Spring异常 | 场景 |
|---------|-------------------|------|
| Hibernate ConstraintViolationException | DataIntegrityViolationException | 违反数据库约束 |
| JPA NoResultException | EmptyResultDataAccessException | 查询无结果 |
| MyBatis PersistenceException | DataAccessException | MyBatis持久化异常 |
| JDBC SQLTimeoutException | QueryTimeoutException | 查询超时 |
| Hibernate LazyInitializationException | InvalidDataAccessApiUsageException | 延迟加载异常 |


2. 内部成员详解
	成员变量:
		repositoryAnnotationType: Class<? extends Annotation>，标记Repository的注解类型，默认为@Repository
	核心方法:
		setRepositoryAnnotationType() - 设置自定义的Repository注解类型
		setBeanFactory() - 设置Bean工厂并创建PersistenceExceptionTranslationAdvisor
3. 类关系结构

ProxyConfig (class)
└── ProxyProcessorSupport (class)
    └── AbstractAdvisingBeanPostProcessor (abstract class)
        └── AbstractBeanFactoryAwareAdvisingPostProcessor (abstract class)
              └── MethodValidationPostProcessor (class)
			  └── PersistenceExceptionTranslationPostProcessor (class)
		      └── AsyncAnnotationBeanPostProcessor (class)
	相关类关系说明:
		AbstractBeanFactoryAwareAdvisingPostProcessor: 父类，提供BeanFactory感知的Advisor应用功能
		PersistenceExceptionTranslationAdvisor: 核心通知器，包含异常转换逻辑
		Repository: 默认的Repository标记注解
		PersistenceExceptionTranslator: 持久化异常转换器接口
		DataAccessException: Spring数据访问异常层次结构的根类
		PersistenceExceptionTranslationPostProcessor专门用于处理持久化异常转换，使应用程序与具体的持久化技术解耦。
4. 使用场景
	数据库访问层异常统一 - 统一处理不同数据库或ORM框架的原生异常
	Repository模式实现 - 为Repository组件提供异常转换能力
	多数据源异常处理 - 在使用多种数据访问技术时提供统一的异常处理
	DAO层异常封装 - 封装DAO层的具体实现细节，提供统一异常接口
	微服务数据访问 - 在微服务架构中统一数据访问异常处理

5. 实际代码应用示例
@Configuration
@EnableTransactionManagement
public class PersistenceConfig {

    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
        return new PersistenceExceptionTranslationPostProcessor();
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        // 配置EntityManagerFactory
        return em;
    }
}


 */
@SuppressWarnings("serial")
public class PersistenceExceptionTranslationPostProcessor extends AbstractBeanFactoryAwareAdvisingPostProcessor {

	private Class<? extends Annotation> repositoryAnnotationType = Repository.class;


	/**
	 * Set the 'repository' annotation type.
	 * The default repository annotation type is the {@link Repository} annotation.
	 * <p>This setter property exists so that developers can provide their own
	 * (non-Spring-specific) annotation type to indicate that a class has a
	 * repository role.
	 * @param repositoryAnnotationType the desired annotation type
	 */
	public void setRepositoryAnnotationType(Class<? extends Annotation> repositoryAnnotationType) {
		Assert.notNull(repositoryAnnotationType, "'repositoryAnnotationType' must not be null");
		this.repositoryAnnotationType = repositoryAnnotationType;
	}

	@Override
	public void setBeanFactory(BeanFactory beanFactory) {
		super.setBeanFactory(beanFactory);

		if (!(beanFactory instanceof ListableBeanFactory)) {
			throw new IllegalArgumentException(
					"Cannot use PersistenceExceptionTranslator autodetection without ListableBeanFactory");
		}
		this.advisor = new PersistenceExceptionTranslationAdvisor(
				(ListableBeanFactory) beanFactory, this.repositoryAnnotationType);
	}

}
